import { Plugin } from "vite";

type HtmlOptions = {
  scripts?: string[];
};

// 追加脚本
const appendScript = (html: string, options: HtmlOptions) => {
  const { scripts } = options;
  if (Array.isArray(scripts) && scripts.length) {
    const result = scripts.map((src) => `<script async src="${src}"></script>`);
    return html.replace("</body>", `${result.join("\n")}\n</body>`);
  } else {
    return html;
  }
};

export default function vitePluginHtml(options: HtmlOptions): Plugin {
  return {
    name: "vite-plugin-html",
    transformIndexHtml(html: string) {
      html = appendScript(html, options);
      return html;
    },
  };
}
